package cc.xuzhi.muggle.admin.handler;

import cc.xuzhi.muggle.common.exception.ServiceException;
import cc.xuzhi.muggle.common.model.Result;
import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class ConsoleExceptionHandler {

    @ExceptionHandler
    public ResponseEntity handleServiceException(ServiceException e) {
        Result error = StringUtils.hasLength(e.getMessage()) ? Result.error(e.getMessage()) : Result.error("请求失败");
        return ResponseEntity.status(HttpStatus.OK)
                .contentType(MediaType.APPLICATION_JSON)
                .body(JSON.toJSONString(error));
    }

    @ExceptionHandler
    public ResponseEntity handleBindException(BindException e) {
        FieldError fieldError = e.getFieldError();
        Result error = Result.error(fieldError.getDefaultMessage());
        return ResponseEntity.status(HttpStatus.OK)
                .contentType(MediaType.APPLICATION_JSON)
                .body(JSON.toJSONString(error));
    }

    @ExceptionHandler
    public ResponseEntity handleException(Exception e) {
        Result error = Result.error(e.getMessage());
        return ResponseEntity.status(HttpStatus.OK)
                .contentType(MediaType.APPLICATION_JSON)
                .body(JSON.toJSONString(error));
    }
}
